<template>
    <el-dialog v-model="showValue" :title="title" width="500" @close="cancel()">
        <el-input v-model.trim="inputValue" autocomplete="off" />
        <div class="tag_container">
            <el-tag 
            class="tag" 
            closable 
            v-for="(key,i) in history" 
            :type="tagTypes[i % 5]"
            @click="inputValue = key"
            @close="removeKey(key)">
            {{key}}
            </el-tag>
        </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="addKey()">
            存为模板
          </el-button>
          <el-button type="primary" @click="save()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script>
import localStore from '../localStore.js'
import { ElMessageBox,ElMessage } from 'element-plus'


  export default{
    props:{
        id:{type:String},
        show:{type:Boolean},
        title:{type:String}
    },
    watch:{
        show(newVal){ this.showValue = newVal}
    },
    data(){
        return{
            inputValue:'',
            history:[],
            showValue:undefined,
            tagTypes:['primary','success','info','warning','danger'],
        }
    },
    methods:{
        cancel(){
            this.$emit('cancel');
            this.$emit('update:show',false);
            this.inputValue = '';
        },
        save(){
            this.$emit('save',this.inputValue);
            this.$emit('update:show',false);
            this.inputValue = '';
        },
        getHistory(){
            if(localStore.getItem(this.id)){
                return JSON.parse(localStore.getItem(this.id));
            }
            else{
                this.setHistory([]);
                return [];
            }
        },
        setHistory(history){
            localStore.setItem(this.id,JSON.stringify(history));
        },
        removeKey(key){
            this.history = this.history.filter(v => v!= key);
            this.setHistory(this.history);
        },
        addKey(){
            if(this.history.indexOf(this.inputValue) >= 0){
                ElMessage({
                    message: '保存失败，模板已存在',
                    type: 'error',
                });
            }
            else{
                this.history.push(this.inputValue);
                this.setHistory(this.history);
            }
        }
    },
    mounted(){
        this.history = this.getHistory();
    },
  }

</script>
<style>
.tag_container{
    margin: 10px 0px;
}
.tag{
    margin: 5px;
    cursor:pointer;
}
</style>